package com.itheima.mobili;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.common.MessageConstant;
import com.itheima.common.RedisConstant;
import com.itheima.common.utils.RedisUtils;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfoVo;
import com.itheima.pojo.Result;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @version V1.0
 * @author: yongjichu
 * @date: 2020/1/18 17:24
 * @description:
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    RedisUtils redisUtils;
    @Reference
    private OrderService orderService;
    @RequestMapping("/submit")
    public Result submit(String deviceId,@RequestBody OrderInfoVo orderInfoVo){
        //首先检验token，防止表单重复提交
        String token = orderInfoVo.getToken();
        if(token==null){
            return Result.error(false,"无效请求");
        }
        //如果token不为空，就根据token名删除这个数据，如果删除后返回影响数据不为0，说明是正确的请求
        Long count = redisUtils.delete(token);
        if(count==0){
            return Result.error(false,"无效请求");
        }
        //校验图片验证码
        String imgCode1=orderInfoVo.getImgCode();
        //获取存入redis中的图片验证码
        String imgCode = redisUtils.get(deviceId);
        if(imgCode==null || !imgCode1.equals(imgCode) ){
            //能进来说明图片验证码不正确
            return Result.error(false,"图片验证码错误");
        }

        //1.校验验证码
         //1.1获取用户输入的验证码和手机号
           //1.1.1验证码
        String validateCode = orderInfoVo.getValidateCode();
           //1.1.2手机号码
        String telephone = orderInfoVo.getTelephone();
          //1.1.3获取之前在redis中存的验证码
        String RedisCode=redisUtils.get(telephone+ RedisConstant.SENDTYPE_ORDER);
          //1.1.4校验验证码
        if(RedisCode==null || !validateCode.equals(RedisCode)){
            //能进来说明验证码输入的不正确
            return Result.error(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //2.调用预约服务
         //2.1首先设置预约的类型
        orderInfoVo.setOrderType(Order.ORDERTYPE_WEIXIN);
        Result result=orderService.submit(orderInfoVo);
        if(result.isFlag()){
            //3.下单成功发送短信
        }
        return result;
    }

    /**
     * 根据order中的id查询数据
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id){
        Result result=null;
        try {
            Result result1=orderService.findByIdDetil(id);
            result=Result.success(true,MessageConstant.QUERY_ORDER_SUCCESS,result1.getData());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(false,MessageConstant.QUERY_ORDER_FAIL);
        }

    }
}
